package com.example.nacosconsumer.Controller;

import com.alibaba.fastjson.JSON;
import com.example.nacosconsumer.ProviderService;
import com.example.nacosconsumer.dao.ForumMapper;
import com.example.nacosconsumer.pojo.Remark;
import com.example.nacosconsumer.pojo.Content;
import com.example.nacosconsumer.pojo.tiezi;
import com.example.nacosconsumer.service.ForumService;
import com.example.nacosconsumer.service.GetRemark_Service;
import com.example.nacosconsumer.util.JsonResult;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@Controller
//@RefreshScope
//@MapperScan(basePackages = {"com.example.nacosconsumer"})
@ComponentScan(basePackages = {"com.example.nacosconsumer"})
@RequestMapping("/forum")
public class ForumController {
    private final ForumMapper forumMapper;
    private final GetRemark_Service remarkService;
    //feign调用其他微服务接口
    private final ProviderService providerService;

    @Autowired
    public ForumController(ForumMapper forumMapper, GetRemark_Service remarkService, ProviderService providerService) {
        this.forumMapper = forumMapper;
        this.remarkService = remarkService;
        this.providerService = providerService;
    }

    @Resource
    ForumService forumService;

    @Resource
    private AmqpTemplate amqpTemplate;



    //论坛URL
    @GetMapping("/luntan")
    public ModelAndView luntan() {
        for (int i = 0; i < 10; i++) {
            amqpTemplate.convertAndSend("myQueue", "第" + i + "条消息");
        }
        ModelAndView model = new ModelAndView("luntan");
        //从Authentication中获取当前用户的用户名
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUser = authentication.getName();
        //根据当前用户获取当前用户头像地址
        String headshotPath = forumMapper.getHeadshotPath(currentUser);

        model.addObject("headshotPath", headshotPath);
        model.addObject("current_user", currentUser);
        return model;
    }
    /**
     * 论坛界面 (已设置分页)
     *
     * @param
     * @return
     * @throws Exception
     */
    @PostMapping("/forum")
    public String luntan(@RequestParam(value = "pageNum") int pageNum, HttpServletRequest request, Model model) throws Exception {
        //从Authentication中获取当前用户的用户名
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUser = authentication.getName();
        //String currentUser = (String) request.getSession().getAttribute("loginUser");
        //设置单页内容数量
        Integer pageSize = 6;
        //指定页码和数量还有对发布时间PublishTime字段设置倒序排序
        PageHelper.startPage(pageNum, pageSize, "publishTime desc");
        //从数据库中获取帖子
        Page<tiezi> tiezi_list = forumMapper.select_tiezi();
        //获取当前页面所有帖子ID 用于获取其子评论
        List<Integer> tieziID_list = tiezi_list.stream().map(tiezi::getID).collect(Collectors.toList());
        //根据帖子ID获取其评论及其子评论
        List<Remark> remark_list = remarkService.selectRemark(tieziID_list);
        //System.out.println(remark_list);
        //根据帖子ID获取点赞数列表以及点赞状态
        for (tiezi tiezi : tiezi_list) {
            tiezi.setStarNum(forumService.starNum(String.valueOf(tiezi.getID()))); //点赞总数
            tiezi.setStarStatu(forumService.isMember(String.valueOf(tiezi.getID()),currentUser));  //点赞状态
        }
        model.addAttribute("tiezi_list", tiezi_list);
        //model.addAttribute("current_user", currentUser);
        model.addAttribute("remark_list", remark_list);
        //modelAndView.addObject("starInfoList", starInfoList);
        //model.addAttribute("headshotPath", headshotPath);
        return "luntan::frame";
    }


    /**
     * 帖子发布函数
     *
     * @param content
     * @param parameter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/publish", method = {RequestMethod.POST})
    public String publish(@RequestBody Content content, @RequestParam Map parameter, HttpServletRequest request) {
        ///从Authentication中获取当前用户的用户名
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUser = authentication.getName();
        System.out.println(content.getContent());
        //调用dao层的存储方法，存储帖子及其用户和时间
        forumMapper.Save_tiezi(currentUser, content.getContent());
        return JSON.toJSONString(new JsonResult<>("ok"));
    }

    /**
     * 评论存储函数
     */
    @ResponseBody
    @RequestMapping(value = "/saveRemark", method = {RequestMethod.POST})
    private String saveRemark(@RequestBody Remark Remark, @RequestParam Map parameter, HttpServletRequest request) {
        try {
            ///从Authentication中获取当前用户的用户名
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String currentUser = authentication.getName();
            forumMapper.savaRemark(currentUser, Remark.getText(), Remark.getParentID());
            parameter.put("msg", "ok");
        } catch (Exception e) {
            parameter.put("msg", "Don't Login");
        }
        //System.out.println(user.toString());
        return JSON.toJSONString(parameter);
    }


    /**
     * 头像图片及路径存储函数
     */
    @PostMapping("/uploadFile")
    @ResponseBody
    public String uploadFile(@RequestPart("file") MultipartFile file, HttpServletRequest request) throws IOException {
        //限制头像大小(20M)
        int MAX_SIZE = 20971520;
        //设置本地存储目录
        String localPath = "/root/springcloud/pictures";
        String fileName = file.getOriginalFilename();
        //创建唯一标识符UUID
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //设置存储路径
        File dest = new File(new File(localPath).getAbsolutePath() + "/" + uuid + fileName);
        System.out.println(file.getSize());
        if (file.getSize() > MAX_SIZE) {
            return JSON.toJSONString(new JsonResult<>("上传的文件大小不能超过20M"));
        }
        // 限制上传的文件类型
        String[] suffixs = new String[]{".png", ".PNG", ".jpg", ".JPG", ".jpeg", ".JPEG", ".gif", ".GIF", ".bmp", ".BMP"};
        SuffixFileFilter suffixFileFilter = new SuffixFileFilter(suffixs);
        if (!suffixFileFilter.accept(dest)){
            return JSON.toJSONString(new JsonResult<>("上传格式不符合"));
        }
        //将接收的到的multipartFile类型的文件转为file存储到本地
        file.transferTo(dest);
        //返回文件路径以便于后续处理
        String filePath = dest.getAbsolutePath();
        //从Authentication中获取当前用户的用户名用于修改用户的头像存储地址
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUser = authentication.getName();
        //修改用户的头像存储地址
        providerService.updateHeadshotPath(currentUser, "http://localhost:8071/pictures/" + uuid + fileName);
        return JSON.toJSONString(new JsonResult<>("上传成功"));
    }

    @ResponseBody
    @GetMapping ("/unAuth")
    public String unAuth() {
        return "无权限访问 请先登录";
    }

    /**
     * 签到服务接口
     * @return 签到信息
     */
    @PostMapping ("/sign")
    @ResponseBody
    public String sign() {
        return forumService.sign();
    }

    /**
     * 点赞服务接口
     * @param tiezi 帖子ID
     * @return 回调信息
     */
    @PostMapping ("/star")
    @ResponseBody
    public String star(@RequestBody Map<String,String> tiezi) {
        System.out.println(tiezi.get("ID"));
        String currentUser = SecurityContextHolder.getContext().getAuthentication().getName();
        Map<String,String> map=new HashMap<>();
        map.put("tiezi_ID", tiezi.get("ID"));
        map.put("currentUser", currentUser);
        amqpTemplate.convertAndSend("Star", map);
        return JSON.toJSONString(new JsonResult<>("操作成功"));
        //return forumService.Star(tiezi.get("ID"));
    }

    //@GetMapping ("/hotRank")
    //public ModelAndView hotList() throws Exception {
    //    ///从Authentication中获取当前用户的用户名
    //    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    //    String currentUser = authentication.getName();
    //    //根据当前用户获取当前用户头像地址
    //    String headshotPath = forumMapper.getHeadshotPath(currentUser);
    //    //指定要加载的网页
    //    ModelAndView modelAndView = new ModelAndView("hotRank");
    //    //设置单页内容数量和页码
    //    Integer pageSize = 3;
    //    Integer pageNum = 1;
    //    //获取点赞数量前三的热帖ID列表
    //    List<Integer> hotIdList = forumService.hotRank();
    //    //指定页码和内容数量
    //    PageHelper.startPage(pageNum, pageSize);
    //    //根据热帖ID列表从数据库中根据获取帖子
    //    Page<tiezi> tiezi_list = forumMapper.getFromID(hotIdList);
    //    System.out.println(tiezi_list.toString());
    //    //
    //    //根据帖子ID获取其评论及其子评论
    //    List<remark> remark_list = remarkService.selectRemark(hotIdList);
    //    //根据帖子ID获取点赞数列表以及点赞状态
    //    for (tiezi tiezi : tiezi_list) {
    //        tiezi.setStarNum(forumService.starNum(String.valueOf(tiezi.getID()))); //点赞总数
    //        tiezi.setStarStatu(forumService.isMember(String.valueOf(tiezi.getID())));  //点赞状态
    //    }
    //    modelAndView.addObject("tiezi_list", tiezi_list);
    //    modelAndView.addObject("current_user", currentUser);
    //    modelAndView.addObject("remark_list", remark_list);
    //    //modelAndView.addObject("starInfoList", starInfoList);
    //    modelAndView.addObject("headshotPath", headshotPath);
    //    //modelAndView.addObject("starInfoList", starInfoList);
    //    return modelAndView;
    //}
}
